<template>
  <!-- 1.通过@vue-office/docx组件 预览word -->
  <!-- <VueOfficeDocx v-if="wordPath" :src="wordPath" style="height: 500px" /> -->
  <!-- 2.通过 docx-preview 插件 预览word -->
  <div ref="docxPreview"></div>
  <input type="file" @change="docxChangePreview" placeholder="选择预览文件" />
  <input
    type="file"
    @change="fillDataDocx"
    placeholder="将数据填充到docx表格里面"
  />
</template>

<script setup>
import { renderAsync } from "docx-preview";
import VueOfficeDocx from "@vue-office/docx";
// 压缩包
import Pizzip from "pizzip";
import Docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";
//引入相关样式
import "@vue-office/docx/lib/index.css";
import { ref } from "vue";

let wordPath = ref("");
let docxPreview = ref(null);

const docxChangePreview = (e) => {
  let file = e.target.files[0];
  // 1.通过@vue-office/docx组件 预览word
  // let fr = new FileReader();
  // fr.readAsDataURL(file);
  // fr.onload = function () {
  //   wordPath.value = fr.result;
  // };
  // 2.通过 docx-preview 插件 预览word
  renderAsync(file, docxPreview.value);
};

const fillDataDocx = (e) => {
  const data = {
    student: [
      { name: "赵倩", id: 1, score: 99 },
      { name: "小学", id: 2, score: 99 },
      { name: "summer", id: 3, score: 100 },
    ]
  };
  const file = e.target.files[0];
  // 将文件转成 arrayBuffer 格式
  file.arrayBuffer().then((res) => {
    // 压缩文件
    let zip = new  Pizzip(res)
    // 创建 Docxtemplater doc
    const doc = new Docxtemplater(zip)
    // 添加数据
    doc.setData(data)
    // 渲染
    doc.render()
    // 转成二进制流
    const out = doc.getZip().generate({
      type: 'blob',
      mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document"'
    })
    // 输出二进制流
    saveAs(out, 'student.docx')
  })
};
</script>

<style lang="less" scoped></style>
